//
//  ConnectionManager.m
//  PCSchool
//
//  Created by Arindam Ghosh on 7/10/13.
//  Copyright (c) 2013 Jayanta. All rights reserved.
//

#import "ConnectionManager.h"
#import "ASIHTTPRequest.h"
#import "DataModel.h"
#import "PCSchoolAppDelegate.h"
#import "JSONKit.h"

@implementation ConnectionManager

@synthesize responseString,webServiceResponce,requestName,request_id,requester,aRequest,handler,appDelegate;



-(id)init{
	if ((self = [super init])) {
		
        self.webServiceResponce = nil;
		self.responseString = nil;
        self.appDelegate = (PCSchoolAppDelegate*) [[UIApplication sharedApplication] delegate];


	}
	return self;
}







#pragma mark - Start Request

-(BOOL)startRequest
{
	
	NSAutoreleasePool* aPool = [[NSAutoreleasePool alloc] init];
    BOOL isRequestSent = NO;
	//[aRequest cancel];
	if([requestName caseInsensitiveCompare:LOGIN] == NSOrderedSame){
        
        //http://203.143.236.47/PCSchoolWebAPI/api/Authentication/GetAuthenticatedUser?LoginName=ahernz14&Password=password&HostAddress=Padua
        
        NSDictionary* aDict = [requester postData];
        
        NSString *name = [aDict valueForKey:USERID];
        NSString *password = [aDict valueForKey:PASSWORD];
        NSString *hostAddress = [aDict valueForKey:HOST_ADDRESS];

        
        NSString* str = [NSString stringWithFormat:@"Authentication/GetAuthenticatedUser?LoginName=%@&Password=%@&HostAddress=%@",name,password,hostAddress];
        
        isRequestSent = [self sendRequest:str andUserName:LOGIN];
	}
    
    else if([requestName caseInsensitiveCompare:SCHOOL_LIST] == NSOrderedSame){
        
        NSString* str = [NSString stringWithFormat:@"Schools/GetSchools"];

        isRequestSent = [self sendRequest:str andUserName:SCHOOL_LIST];

	}
    
    else if([requestName caseInsensitiveCompare:STUDENT_UDID_UPDATE] == NSOrderedSame){
        
        NSDictionary* aDict = [requester postData];
        
        NSString *UDID = [aDict valueForKey:UPDATED_USERID];
        
        NSString* str = [NSString stringWithFormat:@"Students/StudentUDIDUpdate?id=%@",UDID];
        
        isRequestSent = [self sendRequest:str andUserName:STUDENT_UDID_UPDATE];
        
	}
    else if([requestName caseInsensitiveCompare:CLOSEST_STUDENT_DETAILS] == NSOrderedSame){
        
        NSDictionary* aDict = [requester postData];
        
        NSString *UDID = [aDict valueForKey:UPDATED_USERID];
        NSString *memberCode = [aDict valueForKey:MEMBER_CODE];
        
        NSString* str = [NSString stringWithFormat:@"Students/ClosestStudentData?UDID=%@&MemberCode=%@&MemberHash=%@",self.appDelegate.deviceID,memberCode,UDID];
        
        isRequestSent = [self sendRequest:str andUserName:CLOSEST_STUDENT_DETAILS];
        
	}
	
	
	[aPool release];
	return isRequestSent;
}




-(BOOL)sendRequest:(NSString*) strUrl andUserName:(NSString*) usr{
	
	BOOL isSent = NO;
	NSMutableString* smStr = [[NSMutableString alloc] init];
	self.requestName = usr;
	
	
    
    if ([usr isEqualToString:SCHOOL_LIST]) {
        
        [smStr appendString:[NSString stringWithFormat:@"%@%@",BASE_URL,strUrl]];
    }
    else if ([usr isEqualToString:LOGIN]) {
        
        [smStr appendString:[NSString stringWithFormat:@"%@%@",BASE_URL,strUrl]];
    }
    else if ([usr isEqualToString:STUDENT_UDID_UPDATE]) {
        
        [smStr appendString:[NSString stringWithFormat:@"%@%@",BASE_URL,strUrl]];
    }
    else if ([usr isEqualToString:CLOSEST_STUDENT_DETAILS]) {
        
        [smStr appendString:[[NSString stringWithFormat:@"%@%@",BASE_URL,strUrl] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    }
    
    
	
    
    
    NSURL *url = [NSURL URLWithString:smStr];
    NSLog(@"Requesting %@ :  %@",usr,smStr);
    
    //if ([ASIHTTPRequest isNetworkReachableViaWWAN]) {
    NSLog(@"NetWork is ok----- %@",self.appDelegate.deviceID);
    self.aRequest = [ASIHTTPRequest requestWithURL:url];
    
    if ([usr isEqualToString:STUDENT_UDID_UPDATE])
    {
        // Default becomes POST when you use appendPostData: / appendPostDataFromFile: / setPostBody:

        NSDictionary* aDict = [requester postData];
        NSString *UDID = [aDict valueForKey:UPDATED_USERID];
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:UDID,@"StudentId",self.appDelegate.deviceID,@"UDID", nil];
        [aRequest appendPostData:[dic JSONData]];
        [aRequest setRequestMethod:@"PUT"];
        [aRequest addRequestHeader:@"content-type" value:@"application/json"];
        aRequest.allowCompressedResponse = NO;
        aRequest.useCookiePersistence = NO;
        aRequest.shouldCompressRequestBody = NO;
        
    }
    
    [aRequest setShouldContinueWhenAppEntersBackground:YES];
    [aRequest setDelegate:self];
    [aRequest setUsername:usr];
    [aRequest setTimeOutSeconds:30.0];
    [aRequest performThrottling];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    [aRequest startAsynchronous];
    isSent = YES;
    
    
	[smStr release];
	return isSent;
}



#pragma mark ASIHTTPREQUEST DELEGATES


- (void)requestStarted:(ASIHTTPRequest *)request
{
    
}

- (void)requestFinished:(ASIHTTPRequest *)request{
    
    
    NSLog(@"[self requestName]  %@",[self requestName]);

    NSLog(@"RESPONSE HEADERS   %@",[request responseHeaders]);
    
    dispatch_async(dispatch_get_main_queue(), ^{
        
        
        NSLog(@"\n %@ Data Received in Connection Manager for Request : .... %@ : %@ ",[self requestName],[aRequest.url description], [request responseString]);
        if ([[request responseString] rangeOfString:@"SqlException"].location != NSNotFound) {
            
            NSMutableDictionary *errorDetail = [NSMutableDictionary dictionary];

            [errorDetail setValue:[request responseString] forKey:NSLocalizedDescriptionKey];
            NSError *error = [NSError errorWithDomain:@"PCSchool" code:100 userInfo:errorDetail];
            self.aRequest.error = error;

        }
        else
        {
            self.responseString = request.responseString;

        }
        
        //[self.requester  notifyRequesterWithData:self];
        if ([self.appDelegate.dataModel respondsToSelector:@selector(notifyRequestFinished:)]) {
            
            [self.appDelegate.dataModel  notifyRequestFinished:self];

        }

        
    });
    
    
}



- (void)requestFailed:(ASIHTTPRequest *)request{
	NSLog(@"\n%@ Error Connection Manager for Request : .... %@ : ",[self requestName],[request error]);
    self.responseString = [[request error] localizedDescription];
    [self.appDelegate.dataModel  notifyRequestFinished:self];
	
}


-(void) dealloc
{
    
    [super dealloc];
}




@end